<?php


function sec_session_start() {
	$session_name = 'sec_session_id'; // Set a custom session name
	$secure = false; // Set to true if using https.
	$httponly = true; // This stops javascript being able to access the session id.

	ini_set('session.use_only_cookies', 1); // Forces sessions to only use cookies.
	$cookieParams = session_get_cookie_params(); // Gets current cookies params.
	session_set_cookie_params($cookieParams["lifetime"], $cookieParams["path"], $cookieParams["domain"], $secure, $httponly);
	session_name($session_name); // Sets the session name to the one set above.
	session_start(); // Start the php session
	session_regenerate_id(true); // regenerated the session, delete the old one.
}

function sec_session_start_ajax() {
	$session_name = 'sec_session_id'; // Set a custom session name
	$secure = false; // Set to true if using https.
	$httponly = true; // This stops javascript being able to access the session id.

	ini_set('session.use_only_cookies', 1); // Forces sessions to only use cookies.
	$cookieParams = session_get_cookie_params(); // Gets current cookies params.
	session_set_cookie_params($cookieParams["lifetime"], $cookieParams["path"], $cookieParams["domain"], $secure, $httponly);
	session_name($session_name); // Sets the session name to the one set above.
	session_start(); // Start the php session
	session_regenerate_id(); // regenerated the session, delete the old one.
}

function login($email, $password, $mysqli) {
	// Using prepared Statements means that SQL injection is not possible.
	if ($stmt = $mysqli->prepare("SELECT fen_members.id, username, password, salt, access_level, type FROM fen_members, fen_faculty WHERE fen_members.faculty_id = fen_faculty.id and username = ? LIMIT 1")) {
		$stmt->bind_param('s', $email); // Bind "$email" to parameter.
		$stmt->execute(); // Execute the prepared query.
		$stmt->store_result();
		$stmt->bind_result($user_id, $username, $db_password, $salt, $access_level, $type); // get variables from result.
		$stmt->fetch();
		$password = hash('sha512', $password.$salt); // hash the password with the unique salt.

		if($stmt->num_rows == 1) { // If the user exists
			// We check if the account is locked from too many login attempts
			if(checkbrute($user_id, $mysqli) == true) {
				// Account is locked
				// Send an email to user saying their account is locked
				return false;
			} else {
				if($db_password == $password) { // Check if the password in the database matches the password the user submitted.
					// Password is correct!

				$ip_address = $_SERVER['REMOTE_ADDR']; // Get the IP address of the user.
				$user_browser = $_SERVER['HTTP_USER_AGENT']; // Get the user-agent string of the user.

				$user_id = preg_replace("/[^0-9]+/", "", $user_id); // XSS protection as we might print this value
				$_SESSION['user_id'] = $user_id;
				$username = preg_replace("/[^a-zA-Z0-9\/_|+ .-]/", "", $username); // XSS protection as we might print this value
				$_SESSION['username'] = $username;
				$_SESSION['access_level'] = $access_level;
				$_SESSION['login_string'] = hash('sha512', $password.$ip_address.$user_browser);
				$_SESSION['type'] = $type;
				
				$mysqli->query("INSERT INTO fen_logins (user_id, username, ip, agent, time) VALUES ('$user_id', '$username', '$ip_address', '$user_browser', DATE_ADD(CURRENT_TIMESTAMP, INTERVAL 3 HOUR))");
				// Login successful.
				return true;
				} else {
					// Password is not correct
					// We record this attempt in the database
					$now = time();
					$ip_address = $_SERVER['REMOTE_ADDR']; // Get the IP address of the user.
					$user_browser = $_SERVER['HTTP_USER_AGENT']; // Get the user-agent string of the user.
					$mysqli->query("INSERT INTO fen_login_attempts (id, user_id, username, time, date_added, ip, agent) VALUES (null, '$user_id', '$username', '$now', DATE_ADD(CURRENT_TIMESTAMP, INTERVAL 3 HOUR), '$ip_address', '$user_browser')");
					return false;
				}
			}
		} else {
			// No user exists.
			return false;
		}
	}
}

function checkbrute($user_id, $mysqli) {
	// Get timestamp of current time
	$now = time();
	// All login attempts are counted from the past 2 hours.
	$valid_attempts = $now - (2 * 60 * 60);

	if ($stmt = $mysqli->prepare("SELECT time FROM fen_login_attempts WHERE user_id = ? AND time > '$valid_attempts'")) {
		$stmt->bind_param('i', $user_id);
		// Execute the prepared query.
		$stmt->execute();
		$stmt->store_result();
		// If there has been more than 5 failed logins
		if($stmt->num_rows > 5) {
			return true;
		} else {
			return false;
		}
	}
}

function login_check($mysqli, $security_sign, $security_level) {
	// Check if all session variables are set
	if(isset($_SESSION['user_id'], $_SESSION['username'], $_SESSION['login_string'])) {
		
		
		
		$user_id = $_SESSION['user_id'];
		$login_string = $_SESSION['login_string'];
		$username = $_SESSION['username'];
		$ip_address = $_SERVER['REMOTE_ADDR']; // Get the IP address of the user.
		$user_browser = $_SERVER['HTTP_USER_AGENT']; // Get the user-agent string of the user.
		$access_level = $_SESSION['access_level'];

		if ($stmt = $mysqli->prepare("SELECT status from fen_members WHERE id = '$user_id' and status = '0'")) {
			
			$stmt->bind_param('i', $user_id); // Bind "$user_id" to parameter.
			$stmt->execute(); // Execute the prepared query.
			$stmt->store_result();
			if($stmt->num_rows == 1) {
				return false;
			}
		}

		if ($stmt = $mysqli->prepare("SELECT access_level from fen_members WHERE id = '$user_id' and access_level = '$access_level'")) {
			
			$stmt->bind_param('i', $user_id); // Bind "$user_id" to parameter.
			$stmt->execute(); // Execute the prepared query.
			$stmt->store_result();
			if($stmt->num_rows == 0) {
				return false;
			}
		}
		
		if ($security_sign == '<') {
			
			if ($access_level > $security_level) { return false; }
			
		} else if ($security_sign == '=') {
			
			if ($access_level != $security_level) { return false; }
			
		} else if ($security_sign == '>') {
			
			if ($access_level < $security_level) { return false; }
			
		}
		
		
	
		
		if ($stmt = $mysqli->prepare("SELECT password FROM fen_members WHERE id = ? LIMIT 1")) {
			$stmt->bind_param('i', $user_id); // Bind "$user_id" to parameter.
			$stmt->execute(); // Execute the prepared query.
			$stmt->store_result();

			if($stmt->num_rows == 1) { // If the user exists
				$stmt->bind_result($password); // get variables from result.
				$stmt->fetch();
				$login_check = hash('sha512', $password.$ip_address.$user_browser);
				if($login_check == $login_string) {
					// Logged In!!!!
					return true;
				} else {
					// Not logged in
					return false;
				}
			} else {
				// Not logged in
				return false;
			}
		} else {
			// Not logged in
			return false;
		}
	} else {
		// Not logged in
		return false;
	}
}

function error($code) {
	
	if ($code == '1') {
		echo "Hatalı e-posta adresi veya şifre!";
	} elseif ($code == '2') {
		echo "Bu sayfayı görme yetkiniz yok, lütfen giriş yapınız!";
	} elseif ($code == '3') {
		echo "Şifreniz başarıyla değiştirilmiştir, lütfen giriş yapınız!";
	}
	
}



function get_string_between($string){
	
	$start = "=";
	$end = "-";
	$string = " ".$string;
	$ini = strpos($string,$start);
	if ($ini == 0) return "";
	$ini += strlen($start);
	$len = strpos($string,$end,$ini) - $ini;
	return substr($string,$ini,$len);
}



